const Router = require('koa-router');
const adopt = new Router();
const sqldata = require('./sqldata');

// 添加领养作品
adopt.get('/question',async(ctx)=>{
    let mydata = await new Promise((resolve, reject)=>{
        let val=ctx.request.query;
        const sqlLang =`select * from question order by rand() limit 5;`;
        return sqldata(sqlLang, (err, data)=>{
            if(err) reject(err);
            resolve(data);	// 返回拿到的数据
        })
    })
    for(let i=0;i<mydata.length;i++){
        mydata[i].options=[
            {code:'A',option:mydata[i].Qoption1},
            {code:'B',option:mydata[i].Qoption2},
            {code:'C',option:mydata[i].Qoption3},
            {code:'D',option:mydata[i].Qoption4}
        ]
    }
    ctx.body=mydata;
})
adopt.post('/adopt',async (ctx) => {
    let mydata = await new Promise((resolve, reject)=>{
        let val=ctx.request.body;
        const sqlLang =`INSERT INTO adopt (Pid,Uid,Pname,Page,Pvarie,Pinject,Ftime,Uphone,Uarea,Pintroduction,Photo) VALUES ('${val.Pid}', '${val.Uid}', '${val.Pname}', '${val.Page}', '${val.Pvarie}', '${val.Pinject}', '${val.Ftime}', '${val.Uphone}', '${val.Uarea}', '${val.Pintroduction}','${val.Photo}')`;
        return sqldata(sqlLang, (err, data)=>{
            if(err) reject(err);
            resolve(data);	// 返回拿到的数据
        })
    })
    ctx.body=mydata;
})

module.exports = adopt;